<?php

namespace App\Store\Controllers\Member;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Member\Member;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\SiteStore;
use App\Common\Services\CommonExcelExport;
use App\Store\Models\Account\Account;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Basic\GoodsPricetype;
use App\Store\Models\Member\SiteMemberLv;
use App\Store\Models\Order\OrderSalesGoods;
use Maatwebsite\Excel\Facades\Excel;
use App\Store\Services\Excel\DownloadTemp;
use App\Store\Services\Member\CommonMember;
use Illuminate\Support\Facades\DB;


/**
 * 会员信息
 */
class MemberShoppingLogController extends Controller
{
    /**
     * 获取列表
     */
    public function getlist(Request $request)
    {
        $list = OrderSalesGoods::getShoppingLogList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }


    public function loglist(Request $request){
        //
        $list = OrderSalesGoods::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    public function dodownload(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['id'];
        $row = [['会员电话','姓名','会员卡号','订单编号', '门店名称', '下单时间', '开单门店',//G
         '商品名称', '条码', '商品类别','证书号', '商品标价', '标价', '折扣',//N
         '应收金额','回收金额','积分','金重','件重','销售单价',//T
         '工费','实收金额','价格类型','数量','牌价','料价',//Z
         '是否已换','备注']];//AB
        $options = [
            'E'=>SiteStore::where(['cp_id' => $cp_id])->pluck('store_name')->toArray(),
            'G'=>SiteStore::where(['cp_id' => $cp_id])->pluck('store_name')->toArray(),
            'W'=>GoodsPricetype::where(['cp_id' => $cp_id,'is_del'=>1])->pluck('pricetype_name')->toArray(),
            'AA'=>['是','否']
        ];
        $datawith = [
            'A' => '25',
            'B' => '25',
            'C' => '25',
            'D' => '25',
            'E' => '25',
            'F' => '25',
            'G' => '25',
            'H' => '25',
            'I' => '25',
            'J' => '25',
            'K' => '25',
            'L' => '25',
            'M' => '25',
            'N' => '25',
            'O' => '25',
            'P' => '25',
            'Q' => '25',
            'R' => '25',
            'S' => '25',
            'T' => '25',
            'U' => '25',
            'V' => '25',
            'W' => '25',
            'X' => '25',
            'Y' => '25',
            'Z' => '25',
            'AA' => '25',
            'AB' => '40',
        ];
        $filename = '消费明细导入模板_' . time() . '.xlsx';
        return Excel::download(new DownloadTemp($row, $options, $datawith), $filename);
    }


    public function doexport(Request $request)
    {
        $list=OrderSalesGoods::getShoppingLogList($request)['list'];
        $exceldata = [];
        $row = [
            ['start_store'=>'消费记录'],
            [
                'mobile'=>'会员电话',
                'real_name'=>'会员姓名',
                'mem_card_no'=>'会员卡号',
                'order_sn' => '订单编号',
                // 'store_name' => '门店名称',
                'order_at'=>'下单时间',
                'store_name1' => '开单门店',
                'goods_name' => '商品名称',
                'goods_sn_code' => '条码',
                'goods_category_name' => '商品类别',
                'cf_no'=>'证书号',
                'label_price_old'=>'商品标价',
                'label_price'=>'标价',
                'discount'=>'折扣',
                'total_money'=>'应收金额',
                'sub_recovery_goods_meony'=>'回收金额',
                'order_points'=>'积分',
                'netglod_weight'=>'金重',
                'piece_weight'=>'件重',
                'price'=>'销售单价',
                'cost_price_total' => '工费',
                'cost_price'=>'克销工费',
                'real_total_money'=>'实收金额',
                'goods_pricetype_name'=>'价格类型',
                'count'=>'数量',
                'sales_price' => '牌价',
                'old_recovery_price' => '料价',
                'is_exchange'=>'是否已换',
                'remark'=>'备注',
            ]
        ];

        foreach($list as $val){

            $goods_info =json_decode($val['goodsinfo'],true);
            $exceldata[] = [
                'mobile' => $val['memberinfo']?$val['memberinfo']['mobile']:'',
                'real_name' => $val['memberinfo']?$val['memberinfo']['real_name']:'',
                'mem_card_no'=>$val['memberinfo']?$val['memberinfo']['mem_card_no']:'',
                'order_sn' => isset($val['orderinfo']['order_sn'])?$val['orderinfo']['order_sn']:$val['order_sn'],
                'store_name'=>isset($val['memberinfo']['storeinfo']['store_name'])?$val['memberinfo']['storeinfo']['store_name']:'',
                'order_at'=>isset($val['orderinfo']['order_at'])?date('Y-m-d'.$val['orderinfo']['order_at']):date('Y-m-d',$val['create_at']),
                'store_name1'=>$val['storeinfo']['store_name'],
                'goods_name' => $val['goods_name'],
                'goods_sn_code' => $goods_info['goods_sn_code']?? '',
                'goods_category_name' => $goods_info['goods_category']['category_name'],
                'cf_no'=>$goods_info['cf_no']?? '',
                'label_price_old'=>$val['label_price_old']/100,
                'label_price'=>$val['label_price']/100,
                'discount'=>$val['discount'],
                'total_money'=>$val['total_money']/100,
                'sub_recovery_goods_meony'=>$val['sub_recovery_goods_meony']/100,
                'order_points'=>$val['order_points'],
                'netglod_weight'=>$goods_info['is_code_more']==2?($val['weight']??0): ($goods_info['netglod_weight']?? ''),
                'piece_weight'=>$goods_info['piece_weight']?? '',
                'price'=>$val['price']/100,
                'cost_price_total' => ((($val['cost_price']-$val['cost_price_discount'])*$val['weight'])+($val['pieceprice_fee']*$val['count']))/100,
                'real_total_money'=>$val['real_total_money']/100,
                'goods_pricetype_name'=>isset( $goods_info['goods_pricetype']['goods_pricetype_name'])? $goods_info['goods_pricetype']['goods_pricetype_name']:'',
                'count'=>$val['count'],
                'sales_price' => $val['sales_price']/100,
                'old_recovery_price' => $val['old_recovery_price']/100,
                'is_exchange'=>$val['is_exchange']==2?'是':'否',
                'remark'=>$val['remark'],
                'cost_price'=>empty($val['cost_price'])?'':$val['cost_price']/100
            ];
        }

        $filename = '消费记录导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

    public function doimport(Request $request)
    {

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $filepathname = $request->filepathname;
        if ($filepathname != '' && file_exists(storage_path() . $filepathname) && is_file(storage_path() . $filepathname)) {
            $file = storage_path() . $filepathname;
            $data = Excel::toArray(null, $file)[0];

            $ins_data = [];
            foreach ($data as $key => $val) {
                if ($key == 0) { //表头跳过
                    if(count($val)!=28){
                        return response()->json(['code' => '001', 'msg' =>'导入数据格式错误']);
                    }
                    continue;
                }
                if($val[0]==''){
                    return response()->json(['code' => '001', 'msg' =>($key+1).'行手机号不能为空']);
                }

                if(!preg_match('/^1[3456789]\d{9}$/', $val[0])){
                    return response()->json(['code' => '001', 'msg' =>($key+1).'行手机号不规范']);
                }
                $info = Member::where(['mobile' => $val[0], 'cp_id' => $cp_id])->first();
                $storeinfo = SiteStore::where(['store_name' => $val[4], 'cp_id' => $accountinfo['cp_id']])->first();
                if(!$storeinfo){
                    return response()->json(['code' => '001', 'msg' =>($key+1).'行门店名称错误']);
                }

                $storeinfo_order = SiteStore::where(['store_name' => $val[6], 'cp_id' => $accountinfo['cp_id']])->first();
                if(!$storeinfo_order){
                    return response()->json(['code' => '001', 'msg' =>($key+1).'行开单门店错误']);
                }

                $categoryinfo=GoodsCategory::where(['category_name' => $val[9], 'store_id'=>$storeinfo->id,'cp_id' => $accountinfo['cp_id']])->first();
                if(!$categoryinfo){
                    return response()->json(['code' => '001', 'msg' =>($key+1).'行类目名称错误']);
                }
                if (!$info) {
                    //新建会员
                    $memdata = [
                        'cp_id' => $cp_id,
                        'store_id' => $storeinfo->id,
                        'mobile' => $val[0],
                        'real_name' => $val[1],
                        'mem_card_no' => $val[2] ?? '',
                        'create_at' => time(),
                        'update_at' => time(),
                        'is_old'=>2
                    ];
                    $mem_id=Member::create($memdata)->id;
                    CommonMember::setMemInitPoints($request,$mem_id);
                }else{
                    $mem_id=$info->id;
                }
                $goodsinfo=[
                    'goods_name'=>$val['7'],
                    'goods_sn_code'=>$val['8'],
                    'cf_no'=>$val[10],
                    'goods_category'=>['category_name'=>$val[9]],
                    'goods_pricetype'=>['goods_pricetype_name'=>$val[22]]
                ];


                $item=[
                    'mem_id'=>$mem_id,
                    'order_sn'=>strval($val[3]),
                    'cp_id'=>$cp_id,
                    'store_id'=>$storeinfo_order->id,
                    'create_at'=>strtotime($val[5]),
                    'update_at'=>time(),
                    'goods_name'=>strval($val['7']),
                    'goods_sn_code'=>strval($val['8']),
                    'goods_category_id'=>$categoryinfo?$categoryinfo->id:0,
                    'label_price_old'=>intval($val[12]*100),
                    'label_price'=>intval($val[11]*100),
                    'discount'=>floatval($val[13]),
                    'total_money'=>intval($val[14]*100),
                    'sub_recovery_goods_meony'=>$val[15]*100,
                    'order_points'=>intval($val['16']),
                    'weight'=>floatval($val[17]),
                    'weight_old'=>floatval($val[18]),
                    'price'=>intval($val[19]*100),
                    'cost_price'=>bcsub($val['20']*100,$val[17]),
                    'real_total_money'=>intval($val[21]*100),
                    'count'=>intval($val[23]),
                    'sales_price'=>intval($val[24]*100),
                    'old_recovery_price'=>intval($val[25]*100),
                    'is_exchange'=>$val['26']=='是'?2:1,
                    'remark'=>strval($val[27]),
                    'goodsinfo'=>json_encode($goodsinfo),
                    'is_import'=>2,
                    'audit_status'=>2,
                    'is_gram'=>intval($categoryinfo->is_gram),
                    'is_sujin'=>intval($categoryinfo->is_sujin),

                ];
                $ins_data[]=$item;

            }

            DB::beginTransaction();
            try {
                OrderSalesGoods::insert($ins_data);
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json(['code' => '001', 'msg' => '数据导入失败' . $e->getMessage()]);
            }

            return response()->json(['code' => '000', 'msg' => '数据导入成功']);
        } else {
            return response()->json(['code' => '001', 'msg' => '文件不存在'], 200);
        }
    }

}
